//
//  ReceiverListViewController.m
//  XDLookPic
//
//  Created by XD-XY on 5/26/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "ReceiverListViewController.h"
#import "ReceiverCell.h"
#import "XDHeader.h"
#import "XDTools.h"
#import "Address.h"
#import "WriteOrderViewController.h"


@interface ReceiverListViewController ()

@end

@implementation ReceiverListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    SETSTATUSBARTEXTBLACKCOLORE(NO);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.titleLabel.text = @"收货人信息";
    self.titleLabel.textColor = [UIColor whiteColor];
    self.dataArray = [[NSMutableArray alloc] init];

    self.accessVC = mWriteOrderVC;
    [[NSUserDefaults standardUserDefaults] setObject:@{@"uid":@"1290680",@"username":@"hotfatty",@"password":@"123456"} forKey:kMMyUserInfo];

    [self initViews];
}

-(void)initViews
{
    CGFloat aheight =IOS7?20:0;
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(320-117/2.0f, 4+aheight, 117/2.0f, 40);
    [rightBtn setTitle:@"新建" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    rightBtn.backgroundColor = [UIColor clearColor];
    [rightBtn addTarget:self action:@selector(createReceiver) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:rightBtn];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.contentView.bounds];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0,0, UI_SCREEN_WIDTH, 11)];
    _tableView.tableFooterView.backgroundColor =[UIColor clearColor];
    [self.contentView addSubview:_tableView];
    
    [self getDatas:0];
}

#pragma mark - UITableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_dataArray count]==0){
        return 0;
    }
    NSDictionary * dict = [_dataArray objectAtIndex:indexPath.row];
    CGFloat height = [self xyAutoSizeOfString:dict[@"address"] andSize:CGSizeMake(528/2.0f,1000) andtextFont:12];
    if (height < 24){
        return 115;
    }else{
        return 115-14+height;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName = @"cell";
    ReceiverCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell == nil){
        cell = [[ReceiverCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }
    if([_dataArray count]==0){
        return nil;
    }
 
    if ([[_dataArray objectAtIndex:indexPath.row][@"isdefault"] intValue]==1){
        UIImage * image2 = [UIImage imageNamed:@"receiver_cell_sel"];
        image2 = [image2 resizableImageWithCapInsets:UIEdgeInsetsMake(60,40,50,40)];
        cell.disSelectBg.image = image2;
    }else{
        UIImage * image = [UIImage imageNamed:@"receiver_cell_nor"];
        image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(60,40,50,40)];
        cell.disSelectBg.image =image;
    }

    cell.nameLabel.text = [_dataArray objectAtIndex:indexPath.row][@"username"];
    cell.phoneLabel.text = [_dataArray objectAtIndex:indexPath.row][@"mobile"];
    cell.addressLabel.text = [_dataArray objectAtIndex:indexPath.row][@"address"];
    
    CGRect addressRect = [XDTools xyAutoSizeOfWidget:cell.addressLabel andSize:CGSizeMake(528/2.0f, 1000) andtextFont:12];
    cell.addressLabel.frame = CGRectMake(addressRect.origin.x, height_y(cell.nameLabel)+2+4.5, addressRect.size.width, addressRect.size.height);
    
    cell.editBtn.frame = CGRectMake(452/2.0f-11/2.0f, height_y(cell.addressLabel)+8, 23+11, 23+11);
    cell.tLabel.frame = CGRectMake(width_x(cell.editBtn), cell.editBtn.frame.origin.y+3, 30, cell.editBtn.frame.size.height-3);
    cell.rEditBtn.frame = CGRectMake(cell.editBtn.frame.origin.x, cell.editBtn.frame.origin.y,34+30, 34);
    
    [cell.rEditBtn addTarget:self action:@selector(editingReceiver:) forControlEvents:UIControlEventTouchUpInside];
    cell.rEditBtn.tag = 1000 + [[_dataArray objectAtIndex:indexPath.row][@"address_id"] intValue];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSDictionary * dict = [_dataArray objectAtIndex:indexPath.row];
    self.writeVC.myAddress =[[Address alloc] initWithName:dict[@"username"] phone:dict[@"mobile"] provinceId:dict[@"province"] cityId:nil areadId:nil detail:dict[@"address"]];
    self.writeVC.myAddress.addressId = dict[@"address_id"];
    [self.writeVC refreshInfos];
    
    [self setDefaultReceiver:dict[@"address_id"]];
    
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([_accessVC isEqualToString:mWriteOrderVC]){
        return NO;
    }else{
        return YES;
    }
}

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete){
        [self deleteReceiver:indexPath];
    }
}

#pragma mark - 新建收件人
-(void)createReceiver
{
    CreateReceiverViewController * createVC = [[CreateReceiverViewController alloc] init];
    createVC.delegate = self;
    createVC.accessType = @"create";
    [self.navigationController pushViewController:createVC animated:YES];
}

#pragma mark - 编辑收件人
-(void)editingReceiver:(UIButton *)button
{
    CreateReceiverViewController * createVC = [[CreateReceiverViewController alloc] init];
    createVC.delegate = self;
    createVC.accessType = @"edit";
    createVC.addressid = [NSString stringWithFormat:@"%d",button.tag-1000];
    [self.navigationController pushViewController:createVC animated:YES];
}

#pragma mark - 获取数据
-(void)getDatas:(int)type
{
    NSString * uid = [[[NSUserDefaults standardUserDefaults] objectForKey:@"MYSELF_INFO"] objectForKey:@"uid"];
    NSDictionary * params = @{@"userID":@"1290680"
                           };
    
    ASIHTTPRequest * request = [XDTools getShopRequestWithDict:params API:API_MYADDRESS];
    __weak ASIHTTPRequest * mrequest = request;

    [request setCompletionBlock:^{
        [XDTools hideProgress:mWindow];
        [XDTools hideProgress:self.contentView];
        NSDictionary *tempDict = [XDTools  JSonFromString:[mrequest responseString]];
        if([tempDict[@"status"] intValue]==1){
            if (tempDict[@"data"]){
                [_dataArray removeAllObjects];
                [_dataArray addObjectsFromArray:tempDict[@"data"]];
                [_tableView reloadData];
                if (type==1){
                    if (![_accessVC isEqualToString:mWriteOrderVC]){
                        return;
                    }
                    [self.navigationController popViewControllerAnimated:YES];
                }
            }else{
                [XDTools showNoDataToView:self.contentView];
            }
        }
        
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:mWindow];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    
     [request startAsynchronous];
    if ([_accessVC isEqualToString:mWriteOrderVC]){
        [XDTools showProgress:mWindow];
    }
}

#pragma mark - CreateReceiverViewController Delegate
-(void)theRecerverHadEditSucess
{
    [self getDatas:0];
}

#pragma mark - 设置默认收货人
-(void)setDefaultReceiver:(NSString * )address_id
{
    NSString * uid = [[[NSUserDefaults standardUserDefaults] objectForKey:@"MYSELF_INFO"] objectForKey:@"uid"];
    NSDictionary * params = @{@"userID":@"1290680",
                              @"addressID":address_id
                              };
    
    ASIHTTPRequest *request = [XDTools getShopRequestWithDict:params API:API_SETADDRESSDEFAULT];
    __weak ASIHTTPRequest * mrequest = request;

    [request setCompletionBlock:^{
        [XDTools hideProgress:mWindow];
        NSDictionary *tempDict = [XDTools  JSonFromString:[mrequest responseString]];
        if([tempDict[@"status"] intValue]==1){
            [self getDatas:1];
        }else{
            [XDTools showTips:tempDict[@"msg"] toView:mWindow];
        }
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:mWindow];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    
    [request startAsynchronous];
    if ([_accessVC isEqualToString:mWriteOrderVC]){
        [XDTools showProgress:mWindow];
    }
}

#pragma mark - 删除收货人
-(void)deleteReceiver:(NSIndexPath *)indexPath
{
    NSString * uid = [[[NSUserDefaults standardUserDefaults] objectForKey:@"MYSELF_INFO"] objectForKey:@"uid"];
    NSDictionary * params = @{@"userID":uid,
                              @"addressID":[_dataArray objectAtIndex:indexPath.row][@"address_id"]
                              };
    
    ASIHTTPRequest *request = [XDTools getShopRequestWithDict:params API:API_DELADDRESS];
    __weak ASIHTTPRequest * mrequest = request;

    [request setCompletionBlock:^{
        [XDTools hideProgress:mWindow];
        NSDictionary *tempDict = [XDTools  JSonFromString:[mrequest responseString]];
        if([tempDict[@"status"] intValue]==1){
            [XDTools showTips:tempDict[@"msg"] toView:mWindow];
            [_dataArray removeObjectAtIndex:[indexPath row]];           //删除数组里的数据
            [_tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];                       //删除对应数据的cell
            [_tableView reloadData];
        }else{
            [XDTools showTips:tempDict[@"msg"] toView:mWindow];
        }
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:mWindow];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    
    [request startAsynchronous];
    [XDTools showProgress:mWindow];
}

-(CGFloat )xyAutoSizeOfString:(NSString *)string andSize:(CGSize)size andtextFont:(CGFloat )sizefont
{
    if(!IS_NOT_EMPTY(string)){
        return 0;
    }
    if (IOS7){
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:sizefont],NSFontAttributeName,nil];
        CGSize  actualsize =[string boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
        return actualsize.height;
    }else{
        CGSize strSize = [string sizeWithFont:[UIFont systemFontOfSize:sizefont] constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
        return strSize.height;
    }
}

#pragma mark - 重写父类返回方法
- (void)backPrePage
{
    if ([_accessVC isEqualToString:mWriteOrderVC]){
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
